<template>
  <div>
    <v-alert transition="scale-transition" :value="!!url" type="success">
      <a :href="url">{{url}}</a>
    </v-alert>
    <v-textarea v-model="json" outline placeholder="JSON" rows="30" :rules="rules"/>
    <v-btn round color="primary" dark :loading="loading" @click="submit">submit</v-btn>
  </div>
</template>

<script>
import validator from 'validator'
import { addCollection } from '../services/collection'

const rules = [
  value => {
    if (value) {
      if (!validator.isJSON(value)) {
        return '这不是JSON吧'
      }

      return true
    }

    return '什么都没有'
  }
]

export default {
  data() {
    return {
      json: '{"msg":"Hello World"}',
      loading: false,
      url: '',
      rules
    }
  },
  methods: {
    async submit() {
      if (validator.isJSON(this.json)) {
        this.loading = true
        try {
          const res = await addCollection({
            type: 'json',
            content: this.json
          })

          this.loading = false
          this.url = `//118.24.23.165:4000/${res.data._id}`
        } catch (error) {
          this.loading = false
        }
      }
    }
  }
}
</script>

